package com.itbaizhan.config;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.mysql.cj.jdbc.MysqlXADataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/*自定义mybatisPlus,操控不同的数据库*/
//操控slave数据库
@Configuration
@MapperScan(basePackages = "com.itbaizhan.mapper2",sqlSessionTemplateRef = "slaveSqlSessionTemplate")
public class MybatisConfig2 {

    //配置数据源，首先要告诉mybatis数据是在那里
    @Bean(name = "slaveDataSource")
    public DataSource getDataSource(DBConfig2 db){
        //1.将本地事务注册到Atomikos全局事务中
        //注意：引入的是com.atomikos.jdbc.AtomikosDataSourceBean;
        AtomikosDataSourceBean sourceBean = new AtomikosDataSourceBean();

        //2,设置rm供应商
        sourceBean.setUniqueResourceName("slaveDataSource");
        sourceBean.setXaDataSourceClassName(db.getDriverClassName());
        //3.设置testquery
        sourceBean.setTestQuery("select 1");
        //4.设置超时时间
        sourceBean.setBorrowConnectionTimeout(3);


        //设置mysql连接
        MysqlXADataSource dataSource = new MysqlXADataSource();
        dataSource.setUrl(db.getUrl());
        dataSource.setUser(db.getUsername());
        dataSource.setPassword(db.getPassword());

        sourceBean.setXaDataSource(dataSource);

        return sourceBean;
    }


    //通过数据源创建会话功能
    /**
     * SqlSessionFactory 是mybatis 重要对象
     * @return
     *@Qualifier() 读取spring容器里的对象,把上面的DataSource放进来
     */
    @Bean(name="slaveSqlSessionFactory")
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 负责管理mybatis 的sqlsession  即执行sql语句
     * SqlSessionTemplate 替换默认的mybatis 实现的defalutsqlsession ,
     * 原来默认的defalutsqlsession 不能参与spring事务，不能注入 ， 因为线程不安全
     * @return
     */
    //@Bean 用于告诉@MapperScan 扫描哪个SqlSessionTemplate
    @Bean(name ="slaveSqlSessionTemplate")
    public SqlSessionTemplate getSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory")SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
